<?php
class Admin_UploadController extends Zend_Controller_Action 
{
	private $_params = null;
	protected $_config = null;
	
	public function init() 
	{
		parent::init();
		$this->_helper->layout()->disableLayout();
		$this->_config = Zend_Registry::get('configuration');			
		$this->_params = $this->getRequest()->getParams();		
	}
		
	public function indexAction()
	{		
		$this->view->headLink ()->appendStylesheet ( $this->view->baseUrl ().'/html/js/swfupload/css/default.css' );
		$this->view->headScript ()->appendFile ( $this->view->baseUrl () . '/html/js/jlib.js', 'text/javascript');
		$this->view->headScript ()->appendFile ( $this->view->baseUrl () . '/html/js/swfupload/swfupload.js', 'text/javascript');
		$this->view->headScript ()->appendFile ( $this->view->baseUrl () . '/html/js/swfupload/swfupload.queue.js', 'text/javascript');
		$this->view->headScript ()->appendFile ( $this->view->baseUrl () . '/html/js/swfupload/handlers.js', 'text/javascript');
		$this->view->config = $this->_config;
	}
	
	public function uploadImageAction()
	{		
		$this->_helper->viewRenderer->setNoRender(true);	
		if (!isset($_FILES["Filedata"]) || !is_uploaded_file($_FILES["Filedata"]["tmp_name"]) || $_FILES["Filedata"]["error"] != 0) {
			echo "ERROR:invalid upload";
			exit(0);
		}
		$album_id = $this->getRequest()->getParam('aid', 0);
		if ($album_id == 0) {
			echo "ERROR:album id is empty";
			exit(0);
		}
		$config = Zend_Registry::get('configuration');
		$extension = $this->getExtension($_FILES["Filedata"]["name"]);
		$imageName =  md5($_FILES["Filedata"]["name"] . date('YmdHis')) . '.' . $extension;	
		$thumbPath = $config->site->upload->image->thumb_dir; 
		$imagePath = $config->site->upload->image->dir;
		$thumbWidth = $config->site->upload->image->thumb_width;
		$thumbHeight = $config->site->upload->image->thumb_height;
		try {
			$image = new Core_Utilities_Image();
			$image->open($_FILES["Filedata"]["tmp_name"])				  
				  ->save($imagePath, $imageName, 90);		
			$image->resize($thumbWidth, $thumbHeight)			  
				  ->save($thumbPath, $imageName, 90);
			
			$cImage = new Admin_Model_Image();
			$data = array();
			$data['name'] = $_FILES["Filedata"]["name"];
			$data['file_name'] = $imageName;
			$data['album_id'] = $album_id;
			$result = $cImage->insert($data);
			if ($result == 0) {
				@unlink($imagePath . $imageName);
				@unlink($thumbPath . $imageName);
			}  
		} catch (Exception $e) {}
				
		echo "FILEID:{$imageName}";
		exit;
	}	
	
	private function getExtension($fileName) {
		$i = strrpos($fileName,".");
		if (!$i) { return ""; }
		$l = strlen($fileName) - $i;
		$ext = substr($fileName,$i+1,$l);
		return $ext;
	}
}